package br.com.gbvbahia.mybooks;

import org.apache.commons.lang3.StringUtils;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import br.com.gbvbahia.commons.Transacao.Transacao;
import br.com.gbvbahia.commons.modelos.EntityInterface;
import br.com.gbvbahia.commons.utils.AndroidUtils;
import br.com.gbvbahia.mybooks.dao.PerfilDAO;
import br.com.gbvbahia.mybooks.modelos.PerfilVO;
import br.com.gbvbahia.mybooks.service.ws.WebService;

public class Perfil extends ActivityMae {
	private static final String TAG1 = "tag1_perfil";
	private static final String TAG2 = "tag2_perfil";
	private static final String TAG3 = "tag3_perfil";
	private WebService service;
	private TextView url;
	private PerfilVO perfil;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final PerfilDAO pDao = new PerfilDAO(getBaseContext());
		service = new WebService(getBaseContext());
		// Sem perfil
		if (pDao.getPerfil() == null
				|| pDao.getPerfil().getSalvoWS() == EntityInterface.FALSE) {
			setContentView(R.layout.perfil_sem);
			criarVisaoSemPerfil();
			// Com perfil
		} else {
			setContentView(R.layout.perfil_com);
			criarVisaoComPerfil(pDao);

		}

	}

	/**
	 * @param pDao
	 */
	private void criarVisaoComPerfil(final PerfilDAO pDao) {
		perfil = pDao.getPerfil();
		final TextView text3 = (TextView) findViewById(R.id.labelPerfilInfo3);
		final TextView text4 = (TextView) findViewById(R.id.labelPerfilInfo4);
		// Recupera viwes nuvem
		final Button btnAtaulizar = (Button) findViewById(R.id.btnPerfilAlterarPerfil);
		final EditText perfilEditText = (EditText) findViewById(R.id.inputPerfilPerfil);
		final EditText emailEditText = (EditText) findViewById(R.id.inputPerfilEmail);
		final EditText senhaEditText = (EditText) findViewById(R.id.inputPerfilSenha);
		popularPerfil(perfilEditText, emailEditText, senhaEditText, perfil);
		// Recupera views local
		final Button btnAtaulizarLocal = (Button) findViewById(R.id.btnPerfilLocalAlterarPerfil);
		final EditText perfilEditTextLocal = (EditText) findViewById(R.id.inputPerfilLocalPerfil);
		final EditText emailEditTextLocal = (EditText) findViewById(R.id.inputPerfilLocalEmail);
		final EditText senhaEditTextLocal = (EditText) findViewById(R.id.inputPerfilLocalSenha);
		popularPerfil(perfilEditTextLocal, emailEditTextLocal,
				senhaEditTextLocal, perfil);
		// URL Direita
		url = (TextView) findViewById(R.id.labelPerfilShowURL);
		String urlText = getString(R.string.urlInfoD);
		url.setText(StringUtils.replace(urlText, "*", perfil.getPerfil()));
		url.setMovementMethod(LinkMovementMethod.getInstance());

		// Tab
		TabHost tabHost = (TabHost) findViewById(R.id.tabhost);
		tabHost.setup();
		// Tab1
		TabSpec tab1 = tabHost.newTabSpec(TAG1);
		tab1.setContent(R.id.tab1);
		tab1.setIndicator(getString(R.string.atualizaNuvemPerfil));
		tabHost.addTab(tab1);
		// Tab2
		TabSpec tab2 = tabHost.newTabSpec(TAG2);
		tab2.setContent(R.id.tab2);
		tab2.setIndicator(getString(R.string.atualizaLocalPerfil));
		tabHost.addTab(tab2);
		// Listener
		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabName) {
				if (TAG1.equals(tabName)) {
					text3.setVisibility(View.GONE);
					text4.setVisibility(View.VISIBLE);

				} else if (TAG2.equals(tabName)) {
					text3.setVisibility(View.VISIBLE);
					text4.setVisibility(View.GONE);
				}
			}
		});

		// Acao botao
		btnAtaulizarLocal.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String emailUp = emailEditTextLocal.getText().toString();
				String senhaUp = senhaEditTextLocal.getText().toString();
				perfil.setEmail(emailUp);
				perfil.setSenha(senhaUp);
				pDao.updatePrepare(perfil);
				perfil = pDao.getPerfil();
				popularPerfil(perfilEditText, emailEditText, senhaEditText,
						perfil);
				popularPerfil(perfilEditTextLocal, emailEditTextLocal,
						senhaEditTextLocal, perfil);
				AndroidUtils.closeVirtualKeyboard(getBaseContext(),
						btnAtaulizarLocal);
				Toast.makeText(getBaseContext(),
						getString(WebService.PERFIL_ATUALIZADO),
						Toast.LENGTH_SHORT).show();
				finish();
			}
		});

		btnAtaulizar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String emailUp = emailEditText.getText().toString();
				String senhaUp = senhaEditText.getText().toString();
				EditText[] toUpdate = new EditText[]{perfilEditText,emailEditText,senhaEditText, perfilEditTextLocal, emailEditTextLocal, senhaEditTextLocal};
				startTransacaoComRede(new AtualizaPerfilNuvem(service, emailUp, senhaUp, pDao, toUpdate));
				AndroidUtils.closeVirtualKeyboard(getBaseContext(),
						btnAtaulizar);
			}
		});
	}

	/**
	 * @param perfilEditText
	 * @param emailEditText
	 * @param senhaEditText
	 */
	private void popularPerfil(final EditText perfilEditText,
			final EditText emailEditText, final EditText senhaEditText,
			final PerfilVO perfil) {
		perfilEditText.setText(perfil.getPerfil());
		perfilEditText.setEnabled(false);
		emailEditText.setText(perfil.getEmail());
		senhaEditText.setText(perfil.getSenha());
	}

	/**
	 * Cria abas para criar o perfil ou carregar o mesmo.
	 */
	private void criarVisaoSemPerfil() {
		// Info
		final TextView text1 = (TextView) findViewById(R.id.labelPerfilInfo1);
		final TextView text2 = (TextView) findViewById(R.id.labelPerfilInfo2);
		final TextView text3 = (TextView) findViewById(R.id.labelPerfilInfo3);
		final TextView text4 = (TextView) findViewById(R.id.labelPerfilInfo4);
		final TextView text5 = (TextView) findViewById(R.id.labelPerfilInfo5);
		final TextView text6 = (TextView) findViewById(R.id.labelPerfilInfo6);
		// View Criar
		final Button btnCriar = (Button) findViewById(R.id.btnPerfilCriar);
		final EditText perfilCriarText = (EditText) findViewById(R.id.inputPerfilCriarPerfil);
		final EditText emailCriarText = (EditText) findViewById(R.id.inputPerfilCriarEmail);

		// View Carregar
		final Button btnCarregar = (Button) findViewById(R.id.btnPerfilCarregar);
		final EditText perfilCarregatText = (EditText) findViewById(R.id.inputPerfilCarregarPerfil);
		final EditText senhaCarregarText = (EditText) findViewById(R.id.inputPerfilCarregarSenha);
		final EditText emailCarregarText = (EditText) findViewById(R.id.inputPerfilCarregarEmail);

		// View Recuperar
		final Button btnRecuperar = (Button) findViewById(R.id.btnPerfilRecuperar);
		final EditText emailRecuperar = (EditText) findViewById(R.id.inputPerfilRecuperarEmail);

		// Google mail
		String emailGoogle = carregarEmail();
		if (!StringUtils.isBlank(emailGoogle)) {
			emailCriarText.setText(emailGoogle);
			emailRecuperar.setText(emailGoogle);
			emailCarregarText.setText(emailGoogle);
			perfilCriarText.setText(StringUtils.substringBefore(emailGoogle,
					"@"));
		}
		// Tab
		TabHost tabHost = (TabHost) findViewById(R.id.tabhost);
		tabHost.setup();
		// Tab1
		TabSpec tab1 = tabHost.newTabSpec(TAG1);
		tab1.setContent(R.id.tab1);
		tab1.setIndicator(getString(R.string.criarPerfil));
		tabHost.addTab(tab1);
		// Tab2
		TabSpec tab2 = tabHost.newTabSpec(TAG2);
		tab2.setContent(R.id.tab2);
		tab2.setIndicator(getString(R.string.carregarPerfil));
		tabHost.addTab(tab2);
		// Tab3
		TabSpec tab3 = tabHost.newTabSpec(TAG3);
		tab3.setContent(R.id.tab3);
		tab3.setIndicator(getString(R.string.recuperarPerfil));
		tabHost.addTab(tab3);
		// Listener
		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabName) {
				if (TAG1.equals(tabName)) {
					text1.setVisibility(View.VISIBLE);
					text2.setVisibility(View.VISIBLE);
					text3.setVisibility(View.VISIBLE);
					text4.setVisibility(View.VISIBLE);
					text5.setVisibility(View.GONE);
					text6.setVisibility(View.GONE);

				} else if (TAG2.equals(tabName)) {
					text1.setVisibility(View.GONE);
					text2.setVisibility(View.GONE);
					text3.setVisibility(View.GONE);
					text4.setVisibility(View.GONE);
					text5.setVisibility(View.VISIBLE);
					text6.setVisibility(View.GONE);
				} else if (TAG3.equals(tabName)) {
					text1.setVisibility(View.GONE);
					text2.setVisibility(View.GONE);
					text3.setVisibility(View.GONE);
					text4.setVisibility(View.GONE);
					text5.setVisibility(View.GONE);
					text6.setVisibility(View.VISIBLE);
				}
			}
		});

		btnCriar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String login = perfilCriarText.getText().toString();
				String email = emailCriarText.getText().toString();
				if (TextUtils.isEmpty(login) || TextUtils.isEmpty(email)) {
					Toast.makeText(getBaseContext(),
							getString(R.string.aviso_29), Toast.LENGTH_LONG)
							.show();
					return;
				}
				int result = service.criarPerfil(login, email);
				switch (result) {
				case WebService.PERFIL_CRIADO_OK:
					Toast.makeText(getBaseContext(), getString(result),
							Toast.LENGTH_SHORT).show();
					AndroidUtils.closeVirtualKeyboard(getBaseContext(),
							btnCriar);
					Perfil.this.finish();
					break;
				default:
					Toast.makeText(getBaseContext(), getString(result),
							Toast.LENGTH_LONG).show();
					break;
				}

			}
		});

		btnCarregar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String login = perfilCarregatText.getText().toString();
				String senha = senhaCarregarText.getText().toString();
				String email = emailCarregarText.getText().toString();
				if (TextUtils.isEmpty(login) || TextUtils.isEmpty(senha)
						|| TextUtils.isEmpty(email)) {
					Toast.makeText(getBaseContext(),
							getString(R.string.aviso_30), Toast.LENGTH_LONG)
							.show();
					return;
				}
				int result = service.carregarPerfil(login, senha, email);
				switch (result) {
				case WebService.PERFIL_CARREGADO_OK:
					Toast.makeText(getBaseContext(),
							getString(WebService.PERFIL_CARREGADO_OK),
							Toast.LENGTH_SHORT).show();
					AndroidUtils.closeVirtualKeyboard(getBaseContext(),
							btnCarregar);
					Perfil.this.finish();
					break;
				default:
					Toast.makeText(getBaseContext(), getString(result),
							Toast.LENGTH_LONG).show();
					break;
				}
			}
		});

		btnRecuperar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String email = emailRecuperar.getText().toString();
				if (TextUtils.isEmpty(email)) {
					Toast.makeText(getBaseContext(),
							getString(R.string.aviso_44), Toast.LENGTH_LONG)
							.show();
					return;
				}
				int result = service.recuperarDados(email);
				Toast.makeText(getBaseContext(), getString(result),
						Toast.LENGTH_LONG).show();
				AndroidUtils.closeVirtualKeyboard(getBaseContext(),
						btnRecuperar);
			}
		});
	}

	private String carregarEmail() {
		AccountManager am = AccountManager.get(this);
		Account[] accounts = am.getAccountsByType("com.google");
		if (accounts.length > 0) {
			return accounts[0].name;
		}
		return "";
	}

	private class AtualizaPerfilNuvem implements Transacao {
		private WebService service;
		private String emailUp;
		private String senhaUp;
		private PerfilDAO pDao;
		private EditText[] toUpdate;
		private int result;

		public AtualizaPerfilNuvem(WebService service, String emailUp,
				String senhaUp, PerfilDAO pDao, EditText[] toUpdate) {
			super();
			this.service = service;
			this.emailUp = emailUp;
			this.senhaUp = senhaUp;
			this.pDao = pDao;
			this.toUpdate = toUpdate;
		}

		@Override
		public void executar() throws Exception {
			result = service.atualizarPerfil(emailUp, senhaUp);
		}

		@Override
		public void atualizarView() {
			switch (result) {
			case WebService.SEM_CONEXAO:
				Toast.makeText(getBaseContext(),
						getString(WebService.SEM_CONEXAO), Toast.LENGTH_SHORT)
						.show();
				break;
			case WebService.PERFIL_ATUALIZADO:
				perfil = pDao.getPerfil();
				popularPerfil(toUpdate[0], toUpdate[1], toUpdate[2], perfil);
				popularPerfil(toUpdate[3], toUpdate[4], toUpdate[5], perfil);
				Toast.makeText(getBaseContext(),
						getString(WebService.PERFIL_ATUALIZADO),
						Toast.LENGTH_SHORT).show();
				finish();
				break;
			}
		}

	}
}
